<?php
namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Exception;
use Think\Log;
use Common\Vendor\Hook\BaseHook;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CreditVettingModel;
use Think\Cache\Driver\Redis;

class CreditController extends Controller
{

    public function __construct()
    {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    public function enableCredit()
    {
        try {
            $customerId = I('post.customer_id', 0, 'intval');

            $payPass = I('post.pay_pass', 0, 'strval');

            //check pay pass
            D('Customer')->has($customerId);
            $encPayPass = M('Customer')->where(['id' => $customerId])->getField('pay_pass');
            if (!$encPayPass) {
                BusinessException::throwException(Constant::UNSET_PAY_PASS);
            }

            if (password_unmatched($payPass, $encPayPass)) {
                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
            }

            //地理位置
            $country = I("post.country", '');
            $location = I("post.location", '');
            if (empty($country) || empty($location)) {
                BusinessException::throwException(Constant::INVALID_LOCATION);
            }
            //保存位置信息
            $this->saveLocationHistory();

            //获取用户信息
            $data = D("Customer")->where(['id' => $customerId])->find();

            if (!$data['amount']) {
                //同步最新的同盾设备id值
                $tdId = I('post.black_box', '', 'string');
                if(!$tdId){
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
                if(0 == strlen($data['tongdun_device_id']) || $tdId != $data['tongdun_device_id']){
                    if(false == M('Customer')->where(['id' => $customerId])->setField(['tongdun_device_id'=>$tdId])){
                        BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    }
                    $data['tongdun_device_id'] = $tdId;
                }

                //新用户执行决策引擎
                $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data, Constant::TONGDUN_FIRST);
                Log::write("decision exception:" . json_encode($ret));
                if (Constant::SUCCESS != $ret['code']) {
                    BusinessException::throwException($ret['code'], $ret['msg']);
                }

                D("Customer")->where(['id' => $customerId])->
                setField(['amount' => Constant::MAX_AMOUNT_NO_NEED_CHECK, 'balance_amount' => Constant::MAX_AMOUNT_NO_NEED_CHECK]);
                $data['balance_amount'] = $data['amount'] = Constant::MAX_AMOUNT_NO_NEED_CHECK;
            } else {
                $data = [
                    'customer_id' => $customerId,
                    'add_time' => time()
                ];
                $increaseRet = D("IncreaseCredit")->add($data);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                "amount" => Constant::MAX_AMOUNT_NO_NEED_CHECK
            ];
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    //保存位置信息
    private function saveLocationHistory()
    {
        $locationModel = D("CustomerLocationHistory");
        $locationData = [
            'customer_id' => I('post.customer_id', 0, 'intval'),
            'province' => I("post.province", ''),
            'city' => I("post.city", ''),
            'country' => I("post.country", ''),
            'address' => I("post.address", ''),
            'location' => I("post.location", ''),
            'add_time' => time()
        ];
        Log::write("Customer location:" . json_encode($locationData), Log::INFO);
        $locationModel->add($locationData);
    }

    /**************************************************************************
     * 功能描述：提高用户信用额度
     * 创建日期：2016-08-03
     * 入参：
     *     "customer_id": "用户ID",
     *     "country": "用户消费地所在的区/县",
     *     "location": "用户坐标"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     **************************************************************************/
    public function improveCredit()
    {
        try {
            //0.参数校验
            $customerId = I('post.customer_id', 0, 'intval');
            $country = I("post.country", '', 'string');
            $location = I("post.location", '', 'string');
            $password = I("post.pay_pass", '', 'string');
            if(!$customerId || !$country || !$location || !$password) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //1.用户信息校验
            $data = D("Customer")->where(['id' => $customerId])->find();
            if(!count($data)){
                BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
            }
            //老用户才可以直接提高信用额度
            if(!$data['amount']){
                BusinessException::throwException(Constant::NEW_CUSTOMER);
            }

            //校验手机号密码正确性
            if (password_unmatched($password, $data['pay_pass'])) {
                BusinessException::throwException(Constant::PASSWORD_NOT_MATCH);
            }

            //2.申请信用额度在200以上，直接授权提升额度
            if($data['amount'] == Constant::FACILITY_ONE){
                $sql = 'UPDATE customer SET balance_amount = balance_amount + ('.Constant::FACILITY_TWO.'-amount),
                 amount = '.Constant::FACILITY_TWO.' WHERE id = '.$customerId;
                Log::write("用户【customer_id=".$customerId."】：当前信用额度【".$data['amount']."元】，当前追加信用额度-【".Constant::FACILITY_TWO."元】", LOG::INFO);
                if(false === M()->execute($sql)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }

            //3.申请信用额度在500以上，录入数据，等待审核
            if($data['amount'] >= Constant::FACILITY_TWO){
                //设置审核状态
                $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                //检测用户是否已经申请过了
                $check = M('ConsumeHistory')->where("customer_id=".$customerId." and status in (".ConsumeHistoryModel::STATUS_WAIT_REVIEWED.",".ConsumeHistoryModel::STATUS_WAIT_REVIEWEDS.",".ConsumeHistoryModel::STATUS_WAIT_REVIEWEDSS.") and type=".Constant::PAY_TYPE_ZERO_APPLY)->find();
                if($check){
                    BusinessException::throwException(Constant::ALREADY_APPLY);
                }

                //生成零元还款消费记录
                $consumeData = [
                    'amount' => 0,
                    'consume_amount' => 0,
                    'discount_first_order' => 0,
                    'discount_full_amount' => 0,
                    'discount_full_reduce' => 0,
                    'type' => Constant::PAY_TYPE_ZERO_APPLY,
                    'customer_id' => $customerId,
                    'merchant_id' => 0,
                    'status'=>$status,
                    'repayment_time' => strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', strtotime("+1month"))),
                    'add_time' => time()
                ];
                if (!($insertId = D('ConsumeHistory')->add($consumeData))) {
                    BusinessException::throwException(Constant::FAILED);
                }
                //记录信审表
                $creditVetting = [
                    'customer_id' => $customerId,
                    'consume_id' => $insertId,
                    'credit_amount' => 0,
                    'status' => CreditVettingModel::STATUS_WAITING_REVIEW,
                    'type' => Constant::PAY_TYPE_ZERO_APPLY
                ];
                $ins = M('CreditVetting')->add($creditVetting);
                Log::write("[".ACTION_NAME."][记录信审信息][customer_id=".$data['customer_id']."]:".json_encode($creditVetting).",result:".$ins, Log::INFO);


                //3.执行决策是否通过，没有抛异常则通过决策引擎(因为数据要留痕，所以最后做该校验)
                //保存位置信息
                $this->saveLocationHistory();

                //同步最新的同盾设备id值
                $tdId = I('post.black_box', '', 'string');
                if(!$tdId){
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
                if(0 == strlen($data['tongdun_device_id']) || $tdId != $data['tongdun_device_id']){
                    if(false === M('Customer')->where(['id' => $customerId])->setField(['tongdun_device_id'=>$tdId])){
                        BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    }
                    $data['tongdun_device_id'] = $tdId;
                }

                //执行决策
                $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data, Constant::TONGDUN_IMPROVE);
                Log::write("decision exception:" . json_encode($ret));
                if (Constant::SUCCESS != $ret['code']) {
                    D('ConsumeHistory')->where(['id' => $insertId])->setField('status', ConsumeHistoryModel::STATUS_TONDDUN_FAILED);
                    BusinessException::throwException($ret['code'], $ret['msg']);
                }
            }
            $res2App['consume_id'] = $insertId;
            $res2App['amount'] = $data['amount'];
            $res2App['balance_amount'] = $data['balance_amount'];

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res2App;
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 活体检测成功通知
     */
    public function CreditFace()
    {
        try{
            $customerId = I('post.customer_id');
            $facePass = I('post.face_pass');
            $face_score = I('post.mLivenessResult');
            if(!$customerId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //检测用户是否存在，存在则更新，不存在则添加一条数据
            D('Customer')->has($customerId);
            $cur = M('CustomerAuth')->where(['customer_id'=>$customerId])->find();
            
            
            if($cur){
                //更新用户的活体检测认证状态
                $data = [
                    'customer_id' => $customerId,
                    'face_pass' => $facePass
                ];
                
                $upd = M('CustomerAuth')->where(['customer_id'=>$customerId])->save($data);
                
                if($upd < 0){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }else{
                $data = [
                    'customer_id' => $customerId,
                    'id_num' => 1,
                    'face_pass' => $facePass
                ];
                if(!($ins = D('CustomerAuth')->add($data))){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }
            $arr = [
                'face_score'=>$face_score
            ];
            $res = M('Customer')->where(['id'=>$customerId])->save($arr);
            if (empty($res)){
                Log::write("活体分入库失败用户".$customerId."分数".$face_score);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 运营商重新认证
     */
    public function creditMobile()
    {
        try{
            $customerId = I('post.customer_id');
            $consumeId = I('post.consume_id');
            if(!$customerId || !$consumeId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //入参有效性校验
            $customerIdChk = M('ConsumeHistory')->where(['id'=>$consumeId])->getField('customer_id');
            if($customerId != $customerIdChk){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //检测用户是否存在，存在则更新，不存在则报异常（不兼容老数据，如果有老数据进行手动处理）
            D('Customer')->has($customerId);
            $cur = M('CustomerAuth')->where(['customer_id'=>$customerId])->find();
            if($cur){
                if($cur['china_mobile'] != 2){
                    BusinessException::throwException(Constant::CHINA_MOBILE_ERR);
                }
                //更新用户运营商重新认证数据
                $data = [
                    'customer_id' => $customerId,
                    'china_mobile' => 3
                ];
                if(!($upd = M('CustomerAuth')->where(['customer_id'=>$customerId])->save($data))){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $data['status'] = ConsumeHistoryModel::STATUS_WAIT_TWO;
                if(!(D("ConsumeHistory")->where(['id'=>$consumeId])->setField($data))){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }else{
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }


    /**
     * 获取用户已认证信息
     */
    public function getCustomerAuth()
    {
        try{
            $customerId = I('post.customer_id');
            if(!$customerId){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            $customer = D('customer')->has($customerId);
            $cond3 = [
                'mobile'=>$customer['mobile']
            ];
            $certificatedata = M("CertificateData")->where($cond3)->order("add_time DESC")->limit(1)->find();
            if ($customer['id_num'] != $certificatedata['id_num']){
                D('CustomerAuth')->saveCustomerAuth($customerId);
                BusinessException::throwException("亲。。您的运营商认证的身份证和本人填写的身份证不一样哦！");
            }
            // $redis = new Redis();
            // //查询是用户最后一条的记录
            // $res = D('CertificateData')->where($cond3)->order('add_time desc')->limit(1)->find();
            // $china = D('CustomerAuth')->where(['customer_id'=>$customerId])->find();
            // //判断用户上次认证时间
            // $now = time();
            // @$diff = ($now - $res['add_time']);
            // if ($diff > 30 * 24 * 3600 && $china['china_mobile'] == 1){
            //     $scredit = D('CustomerAuth')->saveCustomerAuth($customerId);
            //     if (!$scredit){
            //         BusinessException::throwException(Constant::INVALID_PARAMETER);
            //     }
            //     $czhima = D('Customer')->saveCustomerzhima($customerId);
            //     if (!$czhima){
            //         BusinessException::throwException(Constant::INVALID_PARAMETER);
            //     }
            //     $key = '该用户需要重新认证-'.$customerId;
            //     $redis_res = $redis->set($key,'10');
            //     Log::write('**********|再次拉取客户身份认证：'.$customerId.'|存入Redis中|'.$redis_res);
            // }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $credit = D('CustomerAuth')->getCustomerAuth($customerId);
            if(!$credit){
                BusinessException::throwException(Constant::ID_NUM_NO_AUTHED);
            }
            $ret['data'] = $credit;
            //查询用户订单信息
            // $fconsume = M('ConsumeHistory')->where(['customer_id'=>$customerId,'status'=>3])->order('add_time desc')->limit(1)->find();
            // $paylog = M('CustomerBillPayLog')->where(['consume_id'=>$fconsume['id']])->find();
            // $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$fconsume['id']])->find();
            // $key1 = '该用户需要重新认证-'.$customerId;
            // if (($paylog['amount'] != $consumehistory['amount']) || $redis->get($key1)){
            //     $key2 = '该用户弹窗时间'.$customerId;
            //     if (!$redis->get($key2)){
            //         $key2 = '该用户弹窗时间'.$customerId;
            //         $redis->set($key2,'11');
            //         $test = 1;
            //     } else {
            //         $test = 0;
            //     }
            // } else {
            //     $test = 0;
            // }
            // $ret['data']['tel_re'] = $test?$test:0;
            $ret['data']['extra_info'] = 0;
            
            $zhima = D('CustomerAuth')->getCustomerzhima($customerId);
            if(!$zhima){
                BusinessException::throwException(Constant::NO_ZHIMA);
            }
            $ret['data']['zhima_pass'] = $zhima[0]['sesame_score'];
            $extra = M('CustomerExtraInfo')->where(['customer_id'=>$customerId])->find();
            if($extra){
                $ret['data']['extra_info'] = 1;
            }
            $ret['data']['credit_must'] = Constant::CREDIT_MUST;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 获取认证列表
     */
    public function getAuthList()
    {
        try{
            $customerId = I('post.customer_id');
            if(!$customerId){
                //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            //D('customer')->has($customerId);
            //http://222.73.159.209:9090/#/maibei/mobile/application/
            //https://collect.hulushuju.com/#/maibei/home
            //http://api.9maibei.com/wx_h5/app/index.html#/chm_auth
            $ret = Constant::getReturn(Constant::SUCCESS);
            $list = array(
                'auth_list' => array(
                    array("id"=>"china_mobile", "name"=>"运营商认证", "url"=>"https://collect.hulushuju.com/#/huoyanzichan_CRAWLER/mobile/application/","status"=>"1"),
                    //array("id"=>"taobao_pass", "name"=>"淘宝认证", "url"=>"https://collect.hulushuju.com/#/huoyanzichan_CRAWLER/ecommerce/application/taobao","status"=>"1"),
                    //array("id"=>"jd_pass", "name"=>"京东认证", "url"=>"https://collect.hulushuju.com/#/maibei/ecommerce/application/jingdong","status"=>"1"),
                    //array("id"=>"jd_pass", "name"=>"京东认证", "url"=>"https://collect.hulushuju.com/#/huoyanzichan_CRAWLER/ecommerce/application/jingdong","status"=>"1"),
                    //array("id"=>"alipay_pass", "name"=>"支付宝认证", "url"=>"","status"=>"0"),
                    array("id"=>"zhima_pass", "name"=>"芝麻分认证", "url"=>"http://api.huoyanzichan.com/Home/Zm/","status"=>"1")
                )
            );
            $ret['data'] = $list;

        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /** 上传用户附加信息 **/
    public function uploadContactsInfo()
    {
        try{
            $data = I('post.');
            // var_dump($data);die;
            /******************************************************************************************************************/
            $data_json['user_area'] = $data['user_area'];
            $data_json['marriage_status'] = $data['marriage_status'];
            $data_json['car_loan_status'] = $data['car_loan_status'];
            $data_json['month_income'] = $data['month_income'];
            $data_json['educational_level'] = $data['educational_level'];
            $data_json['proffession'] = $data['proffession'];
            $data_json['company_area'] = $data['company_area'];
            $data_json['ship1'] = $data['ship1'];
            $data_json['mobile1'] = $data['mobile1'];
            $data_json['name1'] = $data['name1'];
            $data_json['ship2'] = $data['ship2'];
            $data_json['mobile2'] = $data['mobile2'];
            $data_json['name2'] = $data['name2'];
            foreach ($data_json as $key => $value) {
                unset($data[$key]);
            }
            // unset($data['user_area']);
            // unset($data['marriage_status']);
            // unset($data['car_loan_status']);
            // unset($data['month_income']);
            // unset($data['educational_level']);
            // unset($data['proffession']);
            // unset($data['company_area']);
            // unset($data['ship1']);
            // unset($data['mobile1']);
            // unset($data['name1']);
            // unset($data['ship2']);
            // unset($data['mobile2']);
            // unset($data['name2']);
            $data['extra_info_json'] = json_encode($data_json);
            /******************************************************************************************************************/
            if(!$data['customer_id']){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has(['id'=>$data['customer_id']]);
            $cur = M('CustomerExtraInfo')->where(['customer_id'=>$data['customer_id']])->find();
            if($cur){
                $cur['ins_time'] = date('Y-m-d H:i:s', time());
                $cur['add_time'] = $cur['update_time'] ? $cur['update_time'] : $cur['add_time'];
                unset($cur['id']);
                unset($cur['update_time']);
                if(!($ins = M('CustomerExtraInfoHis')->add($cur))){
                    Log::write('用户附加信息：res='.json_encode($ins).', sql='.M()->getLastSql(), Log::DEBUG);
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $data['update_time'] = date('Y-m-d H:i:s', time());
                if(!($sav = M('CustomerExtraInfo')->where(['customer_id'=>$data['customer_id']])->save($data))){
                    Log::write('用户附加信息：res='.json_encode($sav).', sql='.M()->getLastSql(), Log::DEBUG);
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }else{
                $data['add_time'] = date('Y-m-d H:i:s', time());
                Log::write('用户附加信息：'.json_encode($data). Log::DEBUG);
                $res = M('CustomerExtraInfo')->add($data);
                if($res === false){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $auth = M('CustomerAuth')->where(['customer_id'=>$data['customer_id']])->find();
                if(!$auth){
                    $auth_data['customer_id'] = $data['customer_id'];
                    $res = M('CustomerAuth')->add($auth_data);
                    if($res === false){
                        BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    }
                }
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*** 获取用户的附加信息 ***/
    public function getContactsInfo()
    {
        try{
            $customer_id = I('post.customer_id', 0, 'int');
            if(!$customer_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $cur = D('Customer')->has(['id'=>$customer_id]);
            $res = M('CustomerExtraInfo')->order('id desc')->where(['customer_id'=>$customer_id])->find();
            $res['user_mobile'] = $cur['mobile'];
            $res['user_name'] = $cur['real_name'];
            $res['id_card_num'] = $cur['id_num'];
            /******************************************************************************************************************/
            $data_arr = json_decode($res['extra_info_json'],true);
            $res['user_area'] = $data_arr['user_area'];
            $res['marriage_status'] = $data_arr['marriage_status'];
            $res['car_loan_status'] = $data_arr['car_loan_status'];
            $res['month_income'] = $data_arr['month_income'];
            $res['educational_level'] = $data_arr['educational_level'];
            $res['proffession'] = $data_arr['proffession'];
            $res['company_area'] = $data_arr['company_area'];
            $res['ship1'] = $data_arr['ship1'];
            $res['mobile1'] = $data_arr['mobile1'];
            $res['name1'] = $data_arr['name1'];
            $res['ship2'] = $data_arr['ship2'];
            $res['mobile2'] = $data_arr['mobile2'];
            $res['name2'] = $data_arr['name2'];
            /******************************************************************************************************************/
            //校验用户是否存在未完成的订单数据或者待还款的数据
            $chk = M('ConsumeHistory')->where(['customer_id'=>$customer_id, 'status'=>['in', '1,2,4,8']])->find();
            if($chk){
                $res['is_can_change'] = 0;//有订单未完成，不可修改信息
            }else{
                $res['is_can_change'] = 1;
            }
            {   //新版app个人资料新增代码
                if (empty($res['extra_info_json'])) {
                    $res['mobile1'] = $res['parent_phone'];
                    $res['name1'] = $res['parent_name'];
                }
                if (empty($res['extra_info_json'])) {
                    $res['mobile2'] = $res['friends_phone'];
                    $res['name2'] = $res['friends_name'];
                }
                // 新老版本app兼容需要注释这里，若只新版不需老版，则打开注释
                // unset($res['parent_phone']);
                // unset($res['parent_name']);
                // unset($res['friends_phone']);
                // unset($res['friends_name']);
                // unset($res['brothers_phone']);
                // unset($res['brothers_name']);
                // unset($res['colleague_phone']);
                // unset($res['colleague_name']);
                unset($res['id']);
                unset($res['customer_id']);
                unset($res['update_time']);
            }
            
            // var_dump($res);die;
            
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /** 修改用户附加信息 **/
    public function changeContactsInfo()
    {
        try{
            $data = I('post.');
            if(!$data['customer_id']){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has(['id'=>$data['customer_id']]);
            $chk = M('ConsumeHistory')->where(['customer_id'=>$data['customer_id'], 'status'=>['in', '1,2,4,8']])->find();
            if($chk){
                BusinessException::throwException(Constant::EDIT_NOWAY);
            }
            $cur = M('CustomerExtraInfo')->where(['customer_id'=>$data['customer_id']])->find();
            if($cur){
                $cur['ins_time'] = date('Y-m-d H:i:s', time());
                $cur['add_time'] = $cur['update_time'] ? $cur['update_time'] : $cur['add_time'];
                unset($cur['id']);
                unset($cur['update_time']);
                if(!($ins = M('CustomerExtraInfoHis')->add($cur))){
                    Log::write('用户附加信息：res='.json_encode($ins).', sql='.M()->getLastSql(), Log::DEBUG);
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $data['update_time'] = date('Y-m-d H:i:s', time());
                if(!($sav = M('CustomerExtraInfo')->where(['customer_id'=>$data['customer_id']])->save($data))){
                    Log::write('用户附加信息：res='.json_encode($sav).', sql='.M()->getLastSql(), Log::DEBUG);
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }else{
                $data['add_time'] = date('Y-m-d H:i:s', time());
                $res = M('CustomerExtraInfo')->add($data);
                if($res === false){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }

            $auth = M('CustomerAuth')->where(['customer_id'=>$data['customer_id']])->find();
            if(!$auth){
                $auth_data['customer_id'] = $data['customer_id'];
                $res = M('CustomerAuth')->add($auth_data);
                if($res === false){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }
}
